package njust.edu.controller;

import com.google.gson.Gson;
import njust.edu.dbutils.UUIDUtil;
import njust.edu.entity.Dish;
import njust.edu.entity.User;
import njust.edu.service.DishService;
import njust.edu.service.impl.DishServiceImpl;
import njust.edu.web.Cart;
import njust.edu.web.DateSale;
import njust.edu.web.DishTypeSale;
import njust.edu.web.Page;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "BookController", value = "/BookController")
public class BookController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    //————————————————————————客户点餐———————————————————————————————————————————————————————————————————————————————————
    DishService dishService = new DishServiceImpl();

    //客户查询某一页的所有菜品
    public void toIndexUI(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        int n = 1;
        String condition = null;
        String likeStr = null;
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        request.setAttribute("user",user);
        try {
            condition = (String) session.getAttribute("bookCondition");
            likeStr = (String) session.getAttribute("bookLikeStr");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (condition == null || ("".trim()).equals(condition)) {
            condition = "id";
        }
        if (likeStr == null) {
            likeStr = "";
        }

        Page<Dish> page = dishService.getPage(n, condition, likeStr);
        request.setAttribute("dishType", dishService.getDishList());
        request.setAttribute("page", page);
        request.getRequestDispatcher("WEB-INF/jsp/book/book.jsp").forward(
                request, response);
    }

    //客户查询所有菜品
    public void allDishList(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        request.setAttribute("dishList", dishService.getAllDishList());
        User user = (User) session.getAttribute("user");
        request.setAttribute("user",user);
        request.getRequestDispatcher("WEB-INF/jsp/book/book.jsp").forward(
                request, response);
    }

    //通过关键字寻找菜品
    public void searchDish(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {

        String likeStr = request.getParameter("likeStr");
        likeStr = likeStr.trim();
        HttpSession session = request.getSession();
        if (likeStr != null) {
            session.setAttribute("bookLikeStr", likeStr);
        } else {
            session.removeAttribute("bookLikeStr");
        }
        response.sendRedirect("BookController?method=toIndexUI");
    }

//    //改变排序方式
//    public void setSortAttr(HttpServletRequest request,
//                            HttpServletResponse response) throws ServletException, IOException {
//        HttpSession session = request.getSession();
//        String conditionStr = request.getParameter("bookCondition");
//        String condition = null;
//        if ("2".equals(conditionStr)) {
//            condition = "sale desc";
//
//        } else if ("3".equals(conditionStr)) {
//            condition = "price desc";
//
//        } else {
//            condition = "";
//
//        }
//
//        session.setAttribute("bookCondition", condition);
//        response.sendRedirect("BookController?method=toIndexUI");
//
//    }

    //客户选择排序方式和关键字查询
    public void searchAndSort(HttpServletRequest request,
                              HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String conditionStr = request.getParameter("bookCondition");
        String likeStr = request.getParameter("likeStr");
        String condition = null;
        likeStr = likeStr.trim();
        if ("2".equals(conditionStr)) {
            condition = "sale desc";

        } else if ("3".equals(conditionStr)) {
            condition = "price desc";

        } else {
            condition = "";

        }
        if (likeStr != null) {
            session.setAttribute("bookLikeStr", likeStr);
        } else {
            session.removeAttribute("bookLikeStr");
        }
        session.setAttribute("bookCondition", condition);
        response.sendRedirect("BookController?method=toIndexUI");

    }

    //————————————————————————管理员操作——————————————————————————————————————————————————————————————————————————————————

    //管理员增加菜品
    public void addDish(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String typeIdStr = request.getParameter("type_id");
        String priceStr = request.getParameter("price");
        String picture = request.getParameter("picture");
        String stockStr = request.getParameter("stock");
        int sale = 0;
        Integer stock = Integer.parseInt(stockStr);
        String description = request.getParameter("description");
        Integer type_id = Integer.parseInt(typeIdStr);
        Float price = Float.parseFloat(priceStr);
        dishService.addBook(id,name, type_id, price, picture, sale, stock, description);
        response.sendRedirect("BookController?method=itemManageUI");
    }

    //增加菜品
    public void itemAddUI(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("dishType", dishService.getDishList());
        request.setAttribute("state", 0);
        request.getRequestDispatcher("WEB-INF/jsp/book/book-add.jsp").forward(
                request, response);
    }

    //管理员删除菜品
    public void itemDelete(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        String pageNum = request.getParameter("pageNum");
        String id = null;
        try {
            id = idStr;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        try {
            dishService.deleteBook(id);
        } catch (Exception e) {
        }
        response.sendRedirect("BookController?method=itemManageUI&pageNum="
                + pageNum);

    }

    //管理员更新菜品信息
    public void itemEdit(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {

        String pageNum = request.getParameter("pageNum");

//        String id = request.getParameter("id");
        String id = "124";
        Dish dish = dishService.getDishById(id);

        String nameStr = request.getParameter("name");
        String name = (nameStr=="")?dish.getName():nameStr;

        String typeIdStr = request.getParameter("type_id");
        Integer type_id = (typeIdStr=="")?dish.getType_id():Integer.parseInt(typeIdStr);

        String priceStr = request.getParameter("price");
        Float price = (priceStr=="")?dish.getPrice():Float.parseFloat(priceStr);

        String pictureStr = request.getParameter("picture");
        String picture = dish.getPicture();

        int sale = dish.getSale();

        String stockStr = request.getParameter("stock");
        Integer stock = (stockStr=="")?dish.getStock():Integer.parseInt(stockStr);

        String descriptionStr = request.getParameter("description");
        String description = (descriptionStr=="")?dish.getDescription():descriptionStr;

        dishService.editBook(id, name, type_id, price, picture, sale, stock, description);
        response.sendRedirect("BookController?method=itemManageUI&pageNum=" + pageNum);
    }

    //更新菜品
    public void itemEditUI(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        String id = idStr;
        Dish dish = dishService.getDishById(id);
        request.setAttribute("dishType", dishService.getDishList());
        request.setAttribute("dish", dish);
        request.setAttribute("state", 1);
        request.getRequestDispatcher("WEB-INF/jsp/book/book-add.jsp").forward(
                request, response);
    }

    //管理员管理菜品
    public void itemManageUI(HttpServletRequest request,
                             HttpServletResponse response) throws ServletException, IOException {

        String pageNumStr = request.getParameter("pageNum");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        request.setAttribute("user",user);
        String condition = null;
        String likeStr = null;
        int pageNum = 1;
        if (pageNumStr!=null)
        {
            try {
                pageNum = Integer.parseInt(pageNumStr);
            } catch (NumberFormatException e) {
            }
        }
        try {
            condition = (String) session.getAttribute("bookCondition");
            likeStr = request.getParameter("search");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (condition == null || ("".trim()).equals(condition)) {
            condition = "id";
        }
        if (likeStr == null) {
            likeStr = "";
        }
        Page<Dish> page = dishService.getPage(pageNum, condition, likeStr);
        request.setAttribute("dishType", dishService.getDishList());
        request.setAttribute("page", page);
        request.getRequestDispatcher("WEB-INF/jsp/book/itemManage.jsp")
                .forward(request, response);
    }

    //销量排行
    public void getTopSaleDish(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Page<Dish> page = dishService.getPage(1, "sale desc", null);
        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        String result = "";
        result = gson.toJson(page.getList());

        out.print(result);
        out.close();

    }

    //各大菜式销量
    public void getSaleDishType(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        List<DishTypeSale> list =dishService.getDishTypeSales();
        PrintWriter out = response.getWriter();

        Gson gson = new Gson();
        String result = "";
        result = gson.toJson(list);
        //System.out.println(result);
        out.print(result);

        out.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        String methodName = request.getParameter("method");
        try {
            Method method = getClass().getDeclaredMethod(methodName,
                    HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
